package com.picshare.controller;

import com.picshare.model.ApiKey;
import com.picshare.model.User;
import com.picshare.service.ApiService;
import com.picshare.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api")
public class ApiKeyController {
    
    @Autowired
    private ApiService apiService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 生成API Key页面
     */
    @GetMapping("/keys")
    public String apiKeyPage(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        List<ApiKey> userKeys = apiService.getUserApiKeys(user.getUsername());
        model.addAttribute("apiKeys", userKeys);
        return "api-keys";
    }
    
    /**
     * 生成新的API Key
     */
    @PostMapping("/keys/generate")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> generateApiKey(@RequestBody Map<String, String> request, 
                                                              HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).body(createErrorResponse("请先登录"));
        }
        
        String description = request.get("description");
        String keyDescription = description != null ? description : "API Key";
        
        try {
            ApiKey apiKey = apiService.createApiKey(user.getUsername(), keyDescription);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("apiKey", apiKey.getKey());
            response.put("description", apiKey.getDescription());
            response.put("createdAt", apiKey.getCreatedAt());
            response.put("message", "API Key生成成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            return ResponseEntity.status(500).body(createErrorResponse("生成API Key失败: " + e.getMessage()));
        }
    }
    
    /**
     * 撤销API Key
     */
    @PostMapping("/keys/revoke")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> revokeApiKey(@RequestBody Map<String, String> request,
                                                            HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).body(createErrorResponse("请先登录"));
        }
        
        String apiKey = request.get("apiKey");
        if (apiKey == null) {
            return ResponseEntity.badRequest().body(createErrorResponse("API Key不能为空"));
        }
        
        try {
            boolean success = apiService.revokeApiKey(apiKey);
            if (success) {
                return ResponseEntity.ok(createSuccessResponse("API Key已撤销"));
            } else {
                return ResponseEntity.badRequest().body(createErrorResponse("API Key不存在或已撤销"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).body(createErrorResponse("撤销API Key失败: " + e.getMessage()));
        }
    }
    
    /**
     * 删除API Key
     */
    @PostMapping("/keys/delete")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> deleteApiKey(@RequestBody Map<String, String> request,
                                                            HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).body(createErrorResponse("请先登录"));
        }
        
        String apiKey = request.get("apiKey");
        if (apiKey == null) {
            return ResponseEntity.badRequest().body(createErrorResponse("API Key不能为空"));
        }
        
        try {
            boolean success = apiService.deleteApiKey(apiKey);
            if (success) {
                return ResponseEntity.ok(createSuccessResponse("API Key已删除"));
            } else {
                return ResponseEntity.badRequest().body(createErrorResponse("API Key不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).body(createErrorResponse("删除API Key失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取用户的API Key列表
     */
    @GetMapping("/keys/list")
    @ResponseBody
    public ResponseEntity<List<ApiKey>> getApiKeys(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).build();
        }
        
        List<ApiKey> userKeys = apiService.getUserApiKeys(user.getUsername());
        return ResponseEntity.ok(userKeys);
    }
    
    private Map<String, Object> createSuccessResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        return response;
    }
    
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
}